﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Basic.第二章.胖瘦通用Context
{
    public class GenericContext
    {
        /// <summary>
        /// 由于内部操作上，所有的容器类型均为Dictionary<string,object>
        /// 所以定义一个固定的类型名称
        /// </summary>
        class NameBasedDictionary : Dictionary<string, object> { }


        /// <summary>
        /// 用于windows应用程序级上下文成员容器
        /// </summary>
        [ThreadStatic]
        private static NameBasedDictionary threadCache;

        /// <summary>
        /// 标识当前应用是否为web应用
        /// </summary>
        private static readonly bool IsWeb = CheckWhetherIsWeb();


        /// <summary>
        /// Web应用中Context保存的键值
        /// </summary>
        private const string ContextKey = "DesignPatternJs.Web";

        /// <summary>
        /// 对于WEb应用，如果HttpContext对应的内容没有初始化，就放置一个空容器
        /// 对于Windows应用，由于ThreadCache为[ThreadStatic]，则无需该过程
        /// </summary>
        public GenericContext()
        {
            if (IsWeb && HttpContext.Current.Items[ContextKey] == null)
                HttpContext.Current.Items[ContextKey] = new NameBasedDictionary();
        }

        /// <summary>
        /// 根据上下文成员名称，返回对应内容
        /// <remarks>
        /// 由于ThreadCache或HttpContext中的缓冲对象都会在构造过程中创建
        /// 因此 这里没有对Cache==null的判断
        /// </remarks>
        /// </summary>
        /// <param name="name">上下文成员键值</param>
        /// <returns>对应内容</returns>
        public object this[string name]
        {
            get
            {
                if (string.IsNullOrEmpty(name)) return null;
                var cache = GetCache();
                if (cache.Count <= 0) return null;
                object result;
                if (cache.TryGetValue(name, out result)) return result;
                return null;
            }
            set
            {
                if (string.IsNullOrEmpty(name)) return;
                var cache = GetCache();
                object temp;
                if (cache.TryGetValue(name, out temp)) cache[name] = value;
                else cache.Add(name, value);
            }
        }

        /// <summary>
        /// 根据应用类型获取相对应的上下文缓冲对象
        /// </summary>
        /// <returns>缓冲对象</returns>
        private static NameBasedDictionary GetCache()
        {
            NameBasedDictionary cache;
            if (IsWeb) cache = (NameBasedDictionary)HttpContext.Current.Items[ContextKey];
            else cache = threadCache;
            if (cache == null) cache = new NameBasedDictionary();
            if (IsWeb)
                HttpContext.Current.Items[ContextKey] = cache;
            else threadCache = cache;
            return cache;
        }

        /// <summary>
        ///判断当前应用是否为Web应用的Helper方法(非官方方法)
        /// </summary>
        /// <returns></returns>
        private static bool CheckWhetherIsWeb()
        {
            var result = false;
            var domain = AppDomain.CurrentDomain;
            try
            {
                var contextType = HttpContext.Current.GetType();
                if (domain.ShadowCopyFiles)
                    result = contextType != null;
            }
            catch (Exception) { return false; }
            return result;
        }
    }
}
